﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Medianamik.Core.Action;
using Medianamik.Core.Interfaces;

namespace Medianamik.Core.Logging
{
   public class LoggingActionHandler :IActionHandler
    {
       private static ActivityLogger _logger;
       protected static ActivityLogger Logger
       {
           get
           {
               return _logger 
                   ?? (_logger = new ActivityLogger());
           }
       }

        #region IActionHandler Members

        public void Initialize(ActionManager events)
        {
            events.AfterCreateNode += events_AfterCreateNode;
            events.AfterDeleteNode  += events_AfterDeleteNode;
            events.AfterUpdateNode += events_AfterUpdateNode;
            events.AfterPublishNodeInstance += events_AfterPublishNodeInstance; 
        }

        

        public string Description
        {
            get { return "Log les modifications faites sur les noeuds dans Médianamik"; }
        }

        #endregion

        #region Events

        void events_AfterCreateNode(ActionEventArgs<Node> args)
        {
            LogNode(args.Item, "Created");
        }
        void events_AfterDeleteNode(ActionEventArgs<Node> args)
        {
            LogNode(args.Item, "Deleted");
        }
        void events_AfterUpdateNode(ActionEventArgs<Node> args)
        {
            LogNode(args.Item, "Updated");
        }

        void events_AfterPublishNodeInstance(ActionEventArgs<NodeInstance> args)
        {
            LogNode(args.Item.Node, "Published");
        }

        void LogNode(Node node, string action)
        {
            string message = null;
            if (node.NodeType.ID == MedianamikTypes.MedianamikTemplate)
                message = "Template " + action;
            else if(!node.NodeType.IsSystem)
                message = "Node " + action;
            if(message != null)
                Logger.Log(node, message);           
        }

        #endregion
    }
}
